package com.lx.yygh.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lx.yygh.common.exception.YyghException;
import com.lx.yygh.common.helper.HttpRequestHelper;
import com.lx.yygh.common.result.ResultCodeEnum;
import com.lx.yygh.enums.OrderStatusEnum;
import com.lx.yygh.enums.PaymentStatusEnum;
import com.lx.yygh.hosp.client.HospFeignClient;
import com.lx.yygh.mapper.OrderMapper;
import com.lx.yygh.mapper.PaymentMapper;
import com.lx.yygh.model.order.OrderInfo;
import com.lx.yygh.model.order.PaymentInfo;
import com.lx.yygh.service.PaymentService;
import com.lx.yygh.vo.order.SignInfoVo;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author c先生
 * @date 2022年11月01日 下午 1:54:56
 * @describe
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, PaymentInfo> implements PaymentService {
    @Autowired
    PaymentMapper paymentMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    HospFeignClient hospFeignClient;

    @Override
    public void savePaymentInfo(OrderInfo order, Integer paymentType) {
        //1 根据订单编号以及支付的类型判断订单是否存在
        String outTradeNo = order.getOutTradeNo();
        QueryWrapper<PaymentInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("out_trade_no",outTradeNo);
        wrapper.eq("payment_type",paymentType);
        Long count = paymentMapper.selectCount(wrapper);
        if(count>0){
            //已经存在支付的信息，直接返回
            return;
        }
        //不存在支付的信息，添加数据到数据库中 保存交易记录
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setOrderId(order.getId());
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOutTradeNo(order.getOutTradeNo());
        paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());
        String subject = new DateTime(order.getReserveDate()).toString("yyyy-MM-dd")+"|"+order.getHosname()+"|"+order.getDepname()+"|"+order.getTitle();
        paymentInfo.setSubject(subject);
        paymentInfo.setTotalAmount(order.getAmount());
        baseMapper.insert(paymentInfo);
    }

    @Override
    public void paySuccess(String outTradeNo, Integer status, Map<String, String> resultMap) {
        //1 根据订单编号得到支付记录
        QueryWrapper<PaymentInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("out_trade_no",outTradeNo);
        wrapper.eq("payment_type",status);
        PaymentInfo paymentInfo = paymentMapper.selectOne(wrapper);

        //2 更新支付记录信息
        paymentInfo.setPaymentStatus(PaymentStatusEnum.PAID.getStatus());
        paymentInfo.setTradeNo(resultMap.get("transaction_id"));
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(resultMap.toString());
        paymentMapper.updateById(paymentInfo);
        //3 根据订单号得到订单信息
        OrderInfo orderInfo = orderMapper.selectById(paymentInfo.getOrderId());
        //4 更新订单信息
        orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());
        orderMapper.updateById(orderInfo);
        //5 调用医院接口，更新订单支付信息
        SignInfoVo signInfoVo = hospFeignClient.getSignInfoVo(orderInfo.getHoscode());
        //设置参数
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode",orderInfo.getHoscode());
        reqMap.put("hosRecordId",orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign", sign);
        JSONObject jsonObject = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl() + "/order/updatePayStatus");
        if(jsonObject.getInteger("code") != 200) {
            throw new YyghException(jsonObject.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
    }

    @Override
    public PaymentInfo getPaymentInfo(Long orderId, Integer paymentType) {
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        queryWrapper.eq("payment_type", paymentType);
        return baseMapper.selectOne(queryWrapper);
    }
}
